package tazmania.entity;

import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;

import tazadum.engine.Entity;
import tazadum.engine.Interval;
import tazadum.engine.Signal;

public class ColorFanBackgroundEntity implements Entity {
	private final float[][] colors = { { 0, 0, 0 }, { 1, 1, 0 }, { 1, 0, 0 } };
	private final Signal signal;

	public ColorFanBackgroundEntity(final Signal signal) {
		this.signal = signal;
	}

	@Override
	public void precalc(final GLAutoDrawable drawable, final float screenRatio) {
	}

	@Override
	public void update(final GLAutoDrawable drawable, final float globalTime, final float localTime, final float dt, final Interval interval) {
		final GL2 gl = drawable.getGL().getGL2();

		gl.glMatrixMode(GL2.GL_PROJECTION);
		gl.glPushMatrix();
		gl.glLoadIdentity();
		gl.glOrtho(0, 640, 480, 0, 0.1f, 1000);
		gl.glMatrixMode(GL2.GL_MODELVIEW);
		gl.glPushMatrix();
		gl.glLoadIdentity();
		gl.glTranslatef(0.0f, 0.0f, -4.0f);

		final float R = signal.channel(Signal.CHANNEL_R);
		final float G = signal.channel(Signal.CHANNEL_G);
		final float B = signal.channel(Signal.CHANNEL_B);

		gl.glEnable(GL.GL_BLEND);
		gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);

		float alpha = 1;
		if (localTime < 2) {
			alpha = localTime * 0.5f;
		} else if (globalTime >= interval.to() - 2) {
			alpha = 1 - (globalTime - (interval.to() - 2)) * .5f;
		}

		gl.glClearColor(R, G, B, 1.0f);
		gl.glDepthRangef(0.1f, 1000);
		gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);

		final float centerX = 320;
		final float centerY = 300;
		final float time = localTime * .2f;

		gl.glPolygonMode(GL.GL_FRONT_AND_BACK, GL2.GL_FILL);

		for (int i = 0; i < 9; i++) {
			final float[] c = colors[i % colors.length];
			gl.glColor4f(c[0], c[1], c[2], alpha);
			final float a = i / 9f;
			fan(gl, centerX, centerY, time, 0.15f, 2 * 3.1415f * a);
		}

		gl.glDisable(GL.GL_BLEND);

		gl.glClear(GL.GL_DEPTH_BUFFER_BIT);
		// gl.glMatrixMode(GL2.GL_MODELVIEW);
		gl.glPopMatrix();
		gl.glMatrixMode(GL2.GL_PROJECTION);
		gl.glPopMatrix();
	}

	private void fan(final GL2 gl, final float centerX, final float centerY, final float time, final float width, final float offset) {
		final float angle1 = offset + time;
		final float angle2 = angle1 + width;
		final float radius = 600;

		gl.glBegin(GL2.GL_TRIANGLES);
		{
			gl.glVertex2f(centerX, centerY);
			gl.glVertex2f(centerX + (float) Math.cos(angle1) * radius, centerY + (float) Math.sin(angle1) * radius);
			gl.glVertex2f(centerX + (float) Math.cos(angle2) * radius, centerY + (float) Math.sin(angle2) * radius);
		}
		gl.glEnd();
	}

	@Override
	public void destroy(final GLAutoDrawable drawable) {
	}
}
